<template>
  <div>
    <i-page-header class="product_tabs" title="短信接口"></i-page-header>
    <Card :bordered="false" dis-hover class="ivu-mt" id="pannel">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="短信记录" name="list">
          <Form ref="smSformValidate" :model="listAc.formValidate">
            <Row type="flex" :gutter="24">
              <Col span="6">
                <FormItem label="手机号码：" label-for="mobile">
                  <Input
                    style="width: 200px"
                    placeholder="请输入手机号码"
                    clearable
                    v-model="listAc.formValidate.mobile"
                  />
                </FormItem>
              </Col>

              <Col span="6">
                <FormItem label="类项" label-for="mobile">
                  <Select
                    style="width: 240px"
                    v-model="listAc.formValidate.is_error"
                    placeholder="请选择"
                    element-id="is_error"
                    clearable
                  >
                    <Option
                      :value="item.id"
                      v-for="(item, index) in listAc.typeSelect"
                      :key="index"
                      >{{ item.name }}</Option
                    >
                  </Select>
                </FormItem>
              </Col>

              <Col span="6">
                <FormItem label="选择日期：">
                  <DatePicker
                    @on-change="tapSmsChangeTime"
                    v-model="listAc.formValidate.timeVal"
                    format="yyyy/MM/dd"
                    type="daterange"
                    placement="bottom-end"
                    placeholder="自定义时间"
                    style="width: 200px"
                  ></DatePicker>
                </FormItem>
              </Col>

              <Col class="ivu-text-right userFrom" span="6">
                <FormItem style="margin-top: 30px">
                  <Button
                    type="primary"
                    icon="ios-search"
                    label="default"
                    class="mr15"
                    @click="getSmsSearch"
                    >搜索
                  </Button>
                </FormItem>
              </Col>
            </Row>
          </Form>
          <div class="fx-r">
            <Button class="mr15" @click="handleSmsSelectAll(true)"
              >设置全选</Button
            >
            <Button @click="handleSmsSelectAll(false)">取消全选</Button>
            <div class="fx-g1"></div>
            <el-button
              v-if="$utils.checkPermissions(paths, 'sms/del')"
              type="danger"
              icon="el-icon-delete"
              label="default"
              @click="tapSmsDelAll"
            >
              删除短信
            </el-button>
          </div>
          <Table
            :columns="listAc.columns"
            :data="listAc.tableData"
            class="mt25"
            ref="smsTable"
            highlight-row
            :loading="listAc.loading"
            no-userFrom-text="暂无数据"
            no-filtered-userFrom-text="暂无筛选结果"
            @on-selection-change="smsSelection"
          >
            <template slot-scope="{ row }" slot="seting">
              <a
                v-if="$utils.checkPermissions(paths, 'sms/del')"
                @click="tapSmsDel(row.id)"
                >删除</a
              >
            </template>

            <template slot-scope="{ row }" slot="status">
              <el-button v-if="row.is_success == 1" type="primary"
                >已发送</el-button
              >
              <el-button v-else type="danger">发送失败</el-button>
            </template>
          </Table>

          <div class="acea-row row-right page">
            <Page
              :total="listAc.page.pageCount"
              show-elevator
              show-total
              @on-change="tapSmsPage"
              :page-size="listAc.page.pageSize"
            />
          </div>
        </el-tab-pane>
        <el-tab-pane
          v-if="$utils.checkPermissions(paths, 'sms/templateList')"
          label="模板配置"
          name="template"
        >
          <div class="fx-r">
            <el-button
              v-if="$utils.checkPermissions(paths, 'sms/templateSave')"
              type="primary"
              @click="tapTempAdd"
              icon="md-add"
              >添加模板</el-button
            >
          </div>

          <Table
            :columns="templateAc.columns"
            :data="templateAc.tableData"
            class="mt25"
            ref="smsTable"
            highlight-row
            :loading="templateAc.loading"
            no-userFrom-text="暂无数据"
            no-filtered-userFrom-text="暂无筛选结果"
          >
            <template slot-scope="{ row, index }" slot="seting">
              <a
                v-if="$utils.checkPermissions(paths, 'sms/templateSave')"
                @click="tapSend(index)"
                class="mr10"
                >测试发送</a
              >
              <a
                v-if="$utils.checkPermissions(paths, 'sms/templateSave')"
                @click="tapTemplateEdit(index)"
                class="mr10"
                >编辑</a
              >
              <a
                v-if="$utils.checkPermissions(paths, 'sms/templateSave')"
                @click="tapTempDel(row.id)"
                >删除</a
              >
            </template>
          </Table>

          <div class="acea-row row-right page">
            <Page
              :total="templateAc.page.pageCount"
              show-elevator
              show-total
              @on-change="tapTempPage"
              :page-size="templateAc.page.pageSize"
            />
          </div>
        </el-tab-pane>
      </el-tabs>
    </Card>

    <el-dialog title="模板操作" :visible.sync="dialogVisible" width="40%">
      <el-form ref="template" :model="templateAc.template" label-width="80px">
        <el-form-item
          label="短信标题"
          prop="title"
          :rules="[{ required: true, message: '短信标题' }]"
        >
          <el-input
            placeholder="短信标题"
            autocomplete="off"
            v-model="templateAc.template.title"
          ></el-input>
        </el-form-item>

        <el-form-item
          label="Code"
          prop="code"
          :rules="[{ required: true, message: '请输入模板唯一标识符' }]"
        >
          <el-input
            placeholder="请输入模板唯一标识符"
            v-model="templateAc.template.code"
          ></el-input>
        </el-form-item>

        <el-form-item label="模板标题">
          <el-input
            type="textarea"
            placeholder="模板数据全部用${name}，表示name是变量!"
            v-model="templateAc.template.content"
          ></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="subAdmin">确 定</el-button>
      </span>
    </el-dialog>

    <!--发送模板-->
    <el-dialog title="模板短信发送" :visible.sync="dialogVisible2" width="40%">
      <el-form ref="template_send" :model="templateAc.send" label-width="80px">
        <el-form-item
          label="手机号码"
          prop="mobile"
          :rules="[{ required: true, message: '手机号码' }]"
        >
          <el-input
            placeholder="手机号码"
            autocomplete="off"
            v-model="templateAc.send.mobile"
          ></el-input>
        </el-form-item>
        <div
          class=""
          v-for="(item, index) in templateAc.send.codeData"
          :key="index"
        >
          <el-form-item :label="item.name">
            <el-input
              @input="tapCodeInput(index)"
              v-model="item.value"
              placeholder="请输入参数"
            ></el-input>
          </el-form-item>
        </div>

        <el-form-item label="短信内容">
          {{ templateAc.send.codeHtml }}
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="subSendAdmin">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import IPageHeader from '../../../../layouts/system/page-header/index'
import {
  SystemSmsDel,
  SystemSmsList,
  SystemSmsTemplateDel,
  SystemSmsTemplateList,
  SystemSmsTemplateSave,
  SystemSmsTemplateGetParam,
  SystemSmsTemplateSend,
} from '../../../../api/system/sms'
import { mapState, mapActions } from 'vuex'
var htmlData = ''
export default {
  name: 'index',
  components: { IPageHeader },
  computed: {
    ...mapState('system/user', ['paths']),
  },
  data() {
    return {
      activeName: 'list',

      tableHeight: 400,
      dialogVisible: false,
      dialogVisible2: false,
      listAc: {
        formValidate: {
          mobile: '',
          timeVal: '',
          is_error: 0,
        },
        tableData: [],
        loading: true,
        selectAr: [],
        typeSelect: [
          { name: '全部', id: 0 },
          { name: '发送成功', id: 1 },
          { name: '发送失败', id: -1 },
        ],
        columns: [
          {
            type: 'selection',
            width: 60,
            align: 'center',
          },
          {
            title: 'ID',
            key: 'id',
            width: 80,
          },
          {
            title: '手机号码',
            key: 'mobile',
            align: 'center',
            width: 100,
          },
          {
            title: '短信信息',
            key: 'content',
          },
          {
            title: '状态',
            slot: 'status',
            width: 140,
          },
          {
            title: '时间',
            key: 'time',
            width: 140,
          },
          {
            title: '操 作',
            slot: 'seting',
            width: 80,
          },
        ],
        page: {
          count: 0, //一共多少数量
          pageSize: 0, //每一页码数量
          page: 1, //当前页码
        },
        isFirst: false,
      },
      templateAc: {
        tableData: [],
        loading: true,
        send: { mobile: '', codeData: [], codeHtml: '', id: 0 },
        columns: [
          {
            title: 'ID',
            key: 'id',
            width: 80,
          },
          {
            title: '短信标题',
            key: 'title',
            align: 'center',
            width: 120,
          },
          {
            title: 'code',
            key: 'code',
            width: 120,
          },
          {
            title: '短信信息',
            key: 'content',
          },
          {
            title: '操 作',
            slot: 'seting',
            width: 140,
          },
        ],
        page: {
          count: 0, //一共多少数量
          pageSize: 0, //每一页码数量
          page: 1, //当前页码
        },
        template: {
          title: '',
          code: '',
          content: '',
          id: 0,
        },
        isFirst: false,
      },
    }
  },

  created() {
    this.initView()
  },
  methods: {
    /**
     *
     */
    initView: function () {
      if (this.activeName == 'list') {
        this.listAc.isFirst = true
        // this.getSmsData()
      }

      if (this.activeName == 'template') {
        this.templateAc.isFirst = true
        // this.getTemplData()
      }
    },
    /**
     * 短信列表
     */
    getSmsData: function () {
      var data = { page: this.listAc.page.page, ...this.listAc.formValidate }
      SystemSmsList(data)
        .then((res) => {
          if (res.code == 200) {
            this.listAc.tableData = res.data.list
            this.listAc.loading = false
            this.listAc.page.pageSize = res.data.pageSize
            this.listAc.page.pageCount = res.data.pageCount
          } else {
            this.listAc.loading = false
            this.$alert(res.msg)
          }
        })
        .catch((err) => {
          this.listAc.loading = false
          this.$utils.loadingClose()
          this.$alert('网络繁忙，加载失败，请稍等片刻在尝试!', '系统提示')
        })
    },
    //smsPage
    tapSmsPage: function (page) {
      this.listAc.loading = true
      this.listAc.page.page = page
      this.getSmsData()
    },
    //选择日期
    tapSmsChangeTime: function () {},
    /**
     * 设置全选
     * @param bool
     */
    handleSmsSelectAll: function (bool) {
      this.$refs.smsTable.selectAll(bool)
    },

    smsSelection: function (selection) {
      this.listAc.selectAr = selection
    },
    /**
     * 搜索栏目
     */
    getSmsSearch: function () {
      this.listAc.loading = true
      this.listAc.page.page = 1
      this.getSmsData()
    },
    /**
     * 删除短信数据
     */
    tapSmsDelAll: function () {
      if (this.listAc.selectAr.length <= 0) {
        this.$alert('请选择进行删除')
        return
      }
      var ids = []
      for (var i in this.listAc.selectAr) {
        ids.push(this.listAc.selectAr[i].id)
      }

      this.$confirm('此操作将永久删除已勾选数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.$utils.loading(this, '删除数据中...')
        SystemSmsDel({ ids: ids.join(',') })
          .then((res) => {
            this.$utils.loadingClose()
            this.loading = true
            if (res.code == 200) {
              this.getSmsData()
            } else {
              this.$alert(res.msg)
            }
          })
          .catch((err) => {
            this.$utils.loadingClose()
            this.$alert('网络繁忙，加载失败，请稍等片刻在尝试!', '系统提示')
          })
      })
    },
    /**
     * 删除某一条短信
     * @param id
     */
    tapSmsDel: function (id) {
      this.$confirm('此操作将永久删除数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.$utils.loading(this, '删除数据中...')
        SystemSmsDel({ ids: id })
          .then((res) => {
            this.$utils.loadingClose()
            this.loading = true
            if (res.code == 200) {
              this.getSmsData()
            } else {
              this.$alert(res.msg)
            }
          })
          .catch((err) => {
            this.$utils.loadingClose()
            this.$alert('网络繁忙，加载失败，请稍等片刻在尝试!', '系统提示')
          })
      })
    },

    handleClick: function (tab, event) {
      if (this.activeName == 'list' && !this.listAc.isFirst) {
        this.listAc.isFirst = true
        // this.getSmsData()
      }
      if (this.activeName == 'template' && !this.templateAc.isFirst) {
        this.templateAc.isFirst = true
        // this.getTemplData()
      }
    },

    /**
     * 短信模板数据
     */
    getTemplData: function () {
      var data = { page: this.templateAc.page.page }
      SystemSmsTemplateList(data)
        .then((res) => {
          if (res.code == 200) {
            this.templateAc.tableData = res.data.list
            this.templateAc.loading = false
            this.templateAc.page.pageSize = res.data.pageSize
            this.templateAc.page.pageCount = res.data.pageCount
          } else {
            this.templateAc.loading = false
            this.$alert(res.msg)
          }
        })
        .catch((err) => {
          this.templateAc.loading = false
          this.$utils.loadingClose()
          this.$alert('网络繁忙，加载失败，请稍等片刻在尝试!', '系统提示')
        })
    },
    tapTempPage: function (page) {
      this.templateAc.loading = true
      this.templateAc.page.page = page
      this.getTemplData()
    },
    /**
     * 添加内容
     */
    tapTempAdd: function () {
      this.templateAc.template = this.$utils.resetFields(
        this.templateAc.template,
        { id: 0 }
      )
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['template'].resetFields()
      })
    },
    /**
     * 编辑数据
     */
    tapTemplateEdit: function (index) {
      this.templateAc.template = JSON.parse(
        JSON.stringify(this.templateAc.tableData[index])
      )
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['template'].resetFields()
      })
    },
    /**
     * 测试发送
     */
    tapSend: function (index) {
      this.$utils.loading(this, '提交数据中...')
      SystemSmsTemplateGetParam({ id: this.templateAc.tableData[index].id })
        .then((res) => {
          this.$utils.loadingClose()
          if (res.code == 200) {
            this.dialogVisible2 = true
            this.templateAc.send.id = this.templateAc.tableData[index].id
            this.templateAc.send.codeData = res.data.data
            htmlData = res.data.content
            this.templateAc.send.codeHtml = res.data.content
            this.templateAc.send.mobile = ''
          } else {
            this.$alert(res.msg)
          }
        })
        .catch((err) => {
          this.$utils.loadingClose()
          this.$alert('网络繁忙，加载失败，请稍等片刻在尝试!', '系统提示')
        })
    },
    /**
     * 获取key数据
     */
    tapCodeInput: function (index) {
      var data = this.templateAc.send.codeData[index]
      var name = data.name
      var v = data.value
      var content = htmlData.replace(name, v)
      this.templateAc.send.codeHtml = content
    },

    /**
     * 添加数据
     */
    subAdmin: function () {
      this.$refs['template'].validate((valid) => {
        if (valid) {
          this.$utils.loading(this, '提交数据中...')
          SystemSmsTemplateSave(this.templateAc.template)
            .then((res) => {
              this.$utils.loadingClose()
              if (res.code == 200) {
                this.$message({
                  message: res.msg,
                  type: 'success',
                })
                this.getTemplData()
                this.dialogVisible = false
              } else {
                this.$alert(res.msg)
              }
            })
            .catch((err) => {
              this.$utils.loadingClose()
              this.$alert('网络繁忙，加载失败，请稍等片刻在尝试!', '系统提示')
            })
        }
      })
    },
    /**
     * 删除某一条短信
     * @param id
     */
    tapTempDel: function (id) {
      this.$confirm('此操作将永久删除数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.$utils.loading(this, '删除数据中...')
        SystemSmsTemplateDel({ ids: id })
          .then((res) => {
            this.$utils.loadingClose()
            this.loading = true
            if (res.code == 200) {
              this.getTemplData()
            } else {
              this.$alert(res.msg)
            }
          })
          .catch((err) => {
            this.$utils.loadingClose()
            this.$alert('网络繁忙，加载失败，请稍等片刻在尝试!', '系统提示')
          })
      })
    },

    subSendAdmin: function () {
      this.$refs['template_send'].validate((valid) => {
        if (valid) {
          this.$utils.loading(this, '提交数据中...')
          SystemSmsTemplateSend({
            id: this.templateAc.send.id,
            mobile: this.templateAc.send.mobile,
            codeData: this.templateAc.send.codeData,
          })
            .then((res) => {
              this.$utils.loadingClose()
              if (res.code == 200) {
                this.$message({
                  message: res.msg,
                  type: 'success',
                })
                this.dialogVisible2 = false
              } else {
                this.$alert(res.msg)
              }
            })
            .catch((err) => {
              this.$utils.loadingClose()
              this.$alert('网络繁忙，加载失败，请稍等片刻在尝试!', '系统提示')
            })
        }
      })
    },
  },
}
</script>
<style scoped></style>
